package com.google.coffeeshop.business;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import vn.bang.utility.JpaUtil;

import com.google.coffeeshop.dao.DAOFactory;
import com.google.coffeeshop.log.Log;

public class CodeGenerationBusiness extends AbstractBaseBusiness {
	
	static public Long getLastestSeatId() {
		final EntityManager entityManager = createEntityManager();
		try {
			return DAOFactory.createSeatDAO(entityManager).findLastestId();
		} catch(PersistenceException persistenceException) {
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return null;
	}
	
	static public String getProductCode() {
		final EntityManager entityManager = createEntityManager();
		try {
			Long lastestId = DAOFactory.createProductDAO(entityManager).findLastestId();
			if (lastestId != null) {
				return "PD" + String.format("%02d", lastestId + 1);
			}
		} catch(PersistenceException persistenceException) {
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return "";
	}
	
	static public String getOrderCode() {
		final EntityManager entityManager = createEntityManager();
		try {
			Long lastestId = DAOFactory.createOrderDAO(entityManager).findLastestId();
			if (lastestId != null) {
				return "EO" + String.format("%07d", lastestId + 1);
			}
		} catch(PersistenceException persistenceException) {
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return "";
	}
	
	static public String getSeatCode() {
		final EntityManager entityManager = createEntityManager();
		try {
			Long lastestId = DAOFactory.createSeatDAO(entityManager).findLastestId();
			if (lastestId != null) {
				return "SE" + String.format("%03d", lastestId + 1);
			}
		} catch(PersistenceException persistenceException) {
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return "";
	}
	
	static public String getEmployeeCode() {
		final EntityManager entityManager = createEntityManager();
		try {
			Long lastestId = DAOFactory.createEmployeeDAO(entityManager).findLastestId();
			if (lastestId != null) {
				return "EM" + String.valueOf(lastestId + 1);
			}
		} catch(PersistenceException persistenceException) {
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return "";
	}
	
	static public String getReceiptNoteCode() {
		final EntityManager entityManager = createEntityManager();
		try {
			Long lastestId = DAOFactory.createReceiptNoteDAO(entityManager).findLastestId();
			if (lastestId != null) {
				return "RN" + String.format("%06d", lastestId + 1);
			}
		} catch(PersistenceException persistenceException) {
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return "";
	}
	
}
